package controllers;


import helpers.Money;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import play.data.validation.Required;
import play.db.jpa.Blob;
import play.db.jpa.JPABase;
import play.mvc.*;

import java.util.*;

import models.*;
import models.Class;

@With(Secure.class) 

public class Application extends Controller {

    public static void index() {
        
    		if(!Money.isMoneypaid())error(Money.getMessage());
    		render();
    	
    }
    
    public static void deleteStudent(Long id) {
    	
    	if(id != null)Student.findById(id)._delete();
    	
    	if(Student.count() == 0) {
            flash.error("No Students in database");
            index();
        }
    	
    	render();
    	
    }
    
    public static void deleteActivity(Long id) {
    	
    	if(id != null){
    		Activity a = Activity.findById(id);
    		while(!a.teachers.isEmpty()) {
    			Teacher t = a.teachers.get(0);
    			a.teachers.remove(t);
    			t.activities.remove(a);
    			t.save();
    			    			
    		}
    		a.delete();
    		
    	}
    	
    	if(Activity.count() == 0) {
            flash.error("No Activities in database");
            index();
        }
    	
    	render();
    	
    }
    
    public static void editAmountToBePaid(Long reg_id,Double amount) {
    	
    	Register r = Register.findById(reg_id);
    	r.amountToBePaid = amount;
    	r.save();
    	view_registration(reg_id);
    	
    	
    }
    
    public static void delete_registration(Long reg_id, Long student_id) {
    	
    	Register r = Register.findById(reg_id);
    	r.delete();
    	browse_registration(student_id);
    }
    
    public static void browse_registration(Long student_id) {
    	
    	if(Register.count() == 0) {
            flash.error("No registrations in database");
            index();
        }
    	
    	Student s = (Student) ((student_id != null)?Student.findById(student_id):Student.findAll().get(0));
    	List<Register> regs = s.registrations;
    	render(regs,student_id);
    }
    
    public static void view_registration(Long registration_id) {
    		
    		Register reg = Register.findById(registration_id);
    		String teacher = reg.teacher.name;
    		String course = reg.course.name+ " - " 
    						+reg.course.activity.name;
    		int n_classes = reg.sClass.size();
    		Double amountToBePaid = reg.amountToBePaid;
    		List<Class> classes = reg.sClass;
    		List<Payement> ps = reg.payments;
    		
    		render(reg,ps,teacher,course,n_classes,amountToBePaid,classes);
    		
    	    		
    }
    
    public static void pay(Long reg_id, Double amount) {
    	
    	Register reg = Register.findById(reg_id);
    	reg.amountToBePaid-=amount;
    	Payement p = new Payement(new Date(), amount, reg);
    	reg.payments.add(p);
    	p.save();
    	reg.save();
    	
    	view_registration(reg_id);
    	
    }
    
    public static void registerCourse(@Required Long student_id,@Required Long course_id, 
    		@Required Long teacher_id,@Required String date1, String date2) {
    	
    	if(Student.count() == 0) {
            flash.error("No students in database");
            index();
        }
    	
    	if(Course.count() == 0) {
            flash.error("No courses in database");
            index();
        }
    	
    	flash.clear();
    	
    	if (!validation.hasErrors()) {
    		
    		Student s = Student.findById(student_id);
    		Course c = Course.findById(course_id);
    		Teacher t = Teacher.findById(teacher_id);
    		
    		Register r = new Register(s,t,c);
    		s.registrations.add(r);
    		t.registrations.add(r);
    		c.registrations.add(r);
    		r.save();
    		s.save();
    		t.save();
    		c.save();
    		
    		LinkedList<Date> dates1 = Register.getMonthDate(date1);
    		
    		if(c.getType().equals("Trinity")) dates1 = Register.getTrinityDate(date1);
    		
    		LinkedList<Date> dates2 = null;
    		if(!date2.equals("")) dates2 = Register.getMonthDate(date2);
    		
    		for(int i=0 ; i<dates1.size() ; i++) {
    			Class c1 = new Class(dates1.get(i), r);
    			r.addClass(c1);
    			c1.save();
    			r.save();
    			
    			if(dates2 !=null && !dates2.isEmpty() && dates2.size()>i) {
    			Class c2 = new Class(dates2.get(i), r);
        		r.addClass(c2);
        		c2.save();
        		r.save();
    			
    			}
    		}
    		
    		view_registration(r.id);
    		
    	}
    	
    	else {
    		
    	Course c = (Course) ((course_id == null) ? Course.findAll().get(0) : Course.findById(course_id));
    	List<Teacher> teachers = c.activity.teachers;	
    	render(c,student_id,course_id,teachers);
    	
    	
    	}
    }
    
    
    
    public static void createCourse(String name, String description, double price,
			String level, Byte type, Long activity_id) {
    	
    	if(Activity.count()==0) {flash.error("No activities in database");index();}
    	if(name != null)
    	{
    	Activity a = Activity.findById(activity_id); 
    	Course c = new Course(name, description, price, level, type, a);
    	a.courses.add(c);
    	c.setCode();
    	c.save();
    	a.save();
    	flash.success("Course created successfully");
    	updateCourse(c.id, null, null, null, null, null, null);
    	}
    	else flash.clear();
    	render();
    	
    }
    
    public static void updateCourse(Long course_id ,String name, String description, Double price,
			String level, Byte type, Long activity_id) {
    	
    	if(Course.count()==0) {flash.error("No courses in database");index();}
    	    	
    	Course c;
    	
    	if(course_id != null && name != null){
    	Activity a = Activity.findById(activity_id);
    	c = Course.findById(course_id);
    	c.name = name;
    	c.description = description;
    	c.price = price;
    	c.level = level;
    	c.type = type;
    	if(c.activity != a){
    	Activity old = c.activity;
    	c.activity.courses.remove(c);
    	c.activity = a;
    	old.save();
    	a.courses.add(c);
    	}
    	c.setCode();
    	c.save();
    	a.save();
    	flash.success("Course updated successfully");
    	}
    	else if(course_id != null) {
    		c = Course.findById(course_id);
    	}
    	
    	else { 
    		c = (Course) Course.findAll().get(0);
    		flash.clear();
    		
    	}
    	
    	render(c,course_id);
    	
    }
    
    
    public static void addTeacherActivity(Long teacher_id, Long activity_id) {
    	
    	List<Activity> activities,teacher_activities = null;
    	List<Teacher> teachers = Teacher.findAll();
    	activities = Activity.findAll();
    	
    	if(teachers.isEmpty()) {flash.error("No teachers in database");index();}
    	if(activities.isEmpty()) {flash.error("No activities in database");index();}
    	
    	if(teacher_id != null && activity_id != null){
    	Teacher t = Teacher.findById(teacher_id);
    	Activity a = Activity.findById(activity_id);
    	t.activities.add(a);
    	a.teachers.add(t);
    	t.save();
    	a.save();
    	flash.success("Activity successfully added");
    	}
    	if(teacher_id != null) {
    		Teacher t = Teacher.findById(teacher_id);
    		teacher_activities = t.activities;
    		for(int i=0 ; i < teacher_activities.size(); i++){
    			activities.remove(teacher_activities.get(i));
    		}
    	}
    	else flash.clear();
    	
    	render(activities,teacher_activities,teachers,teacher_id);
    	
    }
    
    public static void createActivity(String name) {
    	
    	if(name != null){
    	Activity a = new Activity(name);
    	a.save();
    	flash.success("Actitvity "+a.name+" created successfully");
    	}
    	viewActivity();
    }
    
    public static void viewActivity() {
    	
    	List<Activity> activities = Activity.findAll();
    	render(activities);
    	
    	
    }
    
    public static void createStudent(String fname, String lname, String mname, String dateOfBirth,
			String homeAddress, String homePhone, String gender,
			String membershipID, String email1, String email2, 
                        String mobilePhone1, String mobilePhone2, Blob photo) {
    	
        if(fname != null) {
        boolean g = (gender.equals("Male"))?true:false;
        Date d = null;
        
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

	
		try {
			d = formatter.parse(dateOfBirth);
			
		} catch (ParseException e) {
					
		}
        
        Student s = new Student(fname, lname, mname, d, homeAddress, homePhone,g, 
                    membershipID, email1, mobilePhone1);
        
        s.email2 = email2;
        s.mobilePhone2 = mobilePhone2;
        s.save();
        s.generateBarcode();
        s.save();
        s.photo = photo;
        s.save();
        flash.success("Student Created Successfully");
        displayStudents(s.id);      
        }
        
        render();
        
    }
    
    public static void displayStudents(Long id) {
        
        if(Student.count() == 0) {
            flash.error("No students in database");
            index();
        }
        if(id == null) flash.clear();
        List<Student> students = Student.findAll();
        Student s = (Student) ((id == null)?students.get(0):Student.findById(id));
        
        render(students,s,id);
        
    }
    
    public static void updateStudent(Long id, String fname, String lname, String mname, String dateOfBirth,
			String homeAddress, String homePhone, String gender,
			String membershipID, String email1, String email2, 
                        String mobilePhone1, String mobilePhone2, Blob photo) {
        
        if(id != null) {
            
            
        boolean g = (gender.equals("Male"))?true:false;
        Date d = null;
        
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

        try {
		d = formatter.parse(dateOfBirth);
        
        } catch (ParseException e) {}
            
       	Student s = Student.findById(id);
        s.fname = fname;
		s.lname = lname;
		s.mname = mname;
		s.dateOfBirth = d;
		s.homeAddress = homeAddress;
		s.homePhone = homePhone;
		s.gender = g;
		s.MembershipID = membershipID;
		s.email = email1;
		s.mobilePhone = mobilePhone1;
        s.email2 = email2;
        s.mobilePhone2 = mobilePhone2;
        if(photo != null){
        if(s.hasPhoto()) s.photo.getFile().delete();
        s.photo = photo;
        }
        s.save();
        flash.success("Student Updated Successfully");
        }
        
    		displayStudents(id);
        
    }
    
    public static void displayTeachers(Long id) {
        
        if(Teacher.count() == 0) {
            flash.error("No Teachers in database");
            index();
        }
        if(id == null) {
        	flash.clear();
        }
        List<Teacher> teachers = Teacher.findAll();
        Teacher t = (Teacher) ((id == null)?teachers.get(0):Teacher.findById(id));
        render(teachers,t,id);
        
    }
    
    public static void createTeacher(String name, String address, String homePhone,
			String mobilePhone1, String email1, String mobilePhone2, String email2) {
    	
    	if(name != null) {
    	Teacher t = new Teacher(name, address, homePhone, mobilePhone1, email1);
    	t.mobilePhone2 = mobilePhone2;
    	t.email2 = email2;
    	t.save();
    	flash.success("Teacher created Successfully");
        displayTeachers(t.id);
    	}
    	render();
    }
    
    public static void updateTeacher(Long id, String name, String address, String homePhone,
			String mobilePhone1, String email1, String mobilePhone2, String email2) {
    	
    	if(id != null){
    	Teacher t = Teacher.findById(id);
    	t.name = name;
    	t.address = address;
    	t.homePhone = homePhone;
    	t.mobilePhone1 = mobilePhone1;
    	t.email1 = email1;
    	t.mobilePhone2 = mobilePhone2;
    	t.email2 = email2;
    	t.save();
    	flash.success("Teacher updated Successfully");
        
    	}
    	
    	displayTeachers(id);
    }
    
    public static void studentPhoto(Long id) {
 	   Student student = Student.findById(id);
 	   response.setContentTypeIfNotSet(student.photo.type());
 	   renderBinary(student.photo.get());
 	}
    
    public static void uct() {
    	
    	error("Under Construction !");
    	
    }
        

}